package com.example.shop.fgo.ui.activity;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.dd.processbutton.iml.ActionProcessButton;
import com.example.shop.fgo.Constant;
import com.example.shop.fgo.R;
import com.example.shop.fgo.base.YBaseActivity;
import com.example.shop.fgo.entity.LoginEntity;
import com.example.shop.fgo.net.LoginInterServe;
import com.example.shop.fgo.sp.LoginSP;
import com.example.shop.fgo.utils.CookieUtil;
import com.example.shop.library.net.NetJsonUtil;
import com.example.shop.library.util.UtilEdt;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends YBaseActivity implements Callback<LoginEntity> {
    private EditText mEdtServer;
    private EditText mEdtUsername;
    private EditText mEdtUserpwd;
    private Button mBtPwdShow;
    private CheckBox mCbPwdRecord;
    private ActionProcessButton mBtLogin;
    private boolean mIspwd;
    private RelativeLayout mRelUsername;
    private RelativeLayout mRelUerpwd;
    private View.OnClickListener mOnClickListener;



    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mIsHomeOK=true;
                    if (!mHasHome) {
                        doSuccess();
                    }
                case 2:
                    break;
                default:
                    break;
            }
        }
    };
    private Call<LoginEntity> mLoginEntityCall;
    //home的时候是不是网络访问成功了
    private boolean mIsHomeOK;
    //判断用户是否执行了home操作
    private boolean mHasHome;
    @Override
    public int setRootView() {
        return R.layout.activity_main;
    }

    @Override
    public void initViews() {
        mImageView.setVisibility(View.INVISIBLE);
        mTitleLeft.setText("");
        setTitleCenter("登录网盘");

        mRelUsername = (RelativeLayout) findViewById(R.id.rel_username);
        mRelUerpwd = (RelativeLayout) findViewById(R.id.rel_uerpwd);

        mEdtServer = (EditText) findViewById(R.id.edt_server);
        mEdtUsername = (EditText) findViewById(R.id.edt_username);
        mEdtUserpwd = (EditText) findViewById(R.id.edt_userpwd);
        mBtPwdShow = (Button) findViewById(R.id.bt_pwd_show);
        mCbPwdRecord = (CheckBox) findViewById(R.id.cb_pwd_record);
        mBtLogin = (ActionProcessButton) findViewById(R.id.bt_login);
        mEdtUserpwd.setInputType(EditorInfo.TYPE_CLASS_TEXT |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);

        mEdtUsername.setText(LoginSP.getUsername());
        mEdtUserpwd.setTag(LoginSP.getUsepwd());
        //其中有意向不为空，证明上一次登录勾选过记住用户名密码
        if (!TextUtils.isEmpty(LoginSP.getUsername())||!TextUtils.isEmpty(LoginSP.getUsepwd())) {
            mCbPwdRecord.setChecked(true);
        }



        mBtPwdShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIspwd) {
                    //隐藏
                    mEdtUserpwd.setInputType(EditorInfo.TYPE_CLASS_TEXT |EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
                    mBtPwdShow.setText("显示密码");
                }else{
                    //显示
                    mEdtUserpwd.setInputType(EditorInfo.TYPE_CLASS_TEXT);
                    mBtPwdShow.setText("隐藏密码");
                }
                mIspwd=!mIspwd;
            }
        });
        mBtLogin.setMode(ActionProcessButton.Mode.ENDLESS);
        mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doLogin();
            }
        };
        registerBTLoginLis();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mHasHome=false;
        if (mIsHomeOK) {
            doSuccess();
            mIsHomeOK=false;
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mHasHome=true;
    }

    private void doLogin() {
        String uid= UtilEdt.getEdtText(mEdtUsername);
        String passwd=UtilEdt.getEdtText(mEdtUserpwd);
        if (TextUtils.isEmpty(uid)) {
            dyd(mRelUsername);
            return;
        }
        if (TextUtils.isEmpty(passwd)) {
            dyd(mRelUerpwd);
            return;
        }
        if (mCbPwdRecord.isChecked()) {
            LoginSP.saveUsername(uid);
            LoginSP.saveUsepwd(passwd);
        }else{
            LoginSP.saveUsername("");
            LoginSP.saveUsepwd("");
        }


        mBtLogin.setProgress(1);
        LoginInterServe loginInterServe = NetJsonUtil.getRetrofit(Constant.BASE_URL, LoginInterServe.class);
        mLoginEntityCall = loginInterServe.dologin(uid, passwd);
        mLoginEntityCall.enqueue(this);
        //阻止多次点击---解除监听
        unRegisterBTLoginLis();
    }

    private void unRegisterBTLoginLis() {
        mBtLogin.setOnClickListener(null);
    }
    private void registerBTLoginLis() {
        mBtLogin.setOnClickListener(mOnClickListener);
    }

    private void dyd(RelativeLayout relativeLayout) {
        Animation shake = AnimationUtils.loadAnimation(this, R.anim.shake);
        relativeLayout.startAnimation(shake);

    }


    @Override
    public void initDatas() {


    }

    @Override
    public void onResponse(Call<LoginEntity> call, Response<LoginEntity> response) {
        LoginEntity loginEntity = response.body();
        if (loginEntity.isState()) {
            //模拟网络环境较慢
            mHandler.sendEmptyMessageDelayed(1,500);
            CookieUtil.saveCookie(loginEntity.getId(),loginEntity.getToken());
            com.orhanobut.logger.Logger.e(CookieUtil.getCookie());
        }else{
            mBtLogin.setProgress(-1);
            mBtLogin.setText("用户名密码错误");
            registerBTLoginLis();
        }
    }

    @Override
    public void onFailure(Call<LoginEntity> call, Throwable t) {
        mBtLogin.setProgress(-1);
        mBtLogin.setText("网络有问题");
        registerBTLoginLis();
    }
    private boolean cancleNetwork(){
        if (mBtLogin.getProgress()>0) {
            mLoginEntityCall.cancel();
            mBtLogin.setProgress(0);
            registerBTLoginLis();
            mHandler.removeMessages(1);
            return true;
        }

       return false;
    }
    public void doSuccess(){
        mBtLogin.setProgress(100);
        goToActivity(HomeActivity.class);
        finish();
    }
    @Override
    public void onBackPressed() {
        if (!cancleNetwork()) {
            super.onBackPressed();
        }
    }

}
